package com.timoon.component.panel.jqgrid;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class JqGridHelper {

	public Integer rows=10;//分页大小
	public Integer page=1;//目标页码
	public Integer records=10;//总记录数
	public Integer total=1;//总页数
	public Integer startIndex=0;
	
	/**
	 * 将request所有请求参数改成Map<String,String>
	 * @param request
	 * @return
	 */
	public Map<String,String> coverParameterMap(HttpServletRequest request){
		Map<String,String> map=new HashMap<String,String>();
		
		Map<String,String[]> paramsMap=request.getParameterMap();
		
		Iterator<String> it=paramsMap.keySet().iterator();
		while(it.hasNext()){
			String key=it.next();
			String value=paramsMap.get(key)[0];
			if(!value.equals("")){
				map.put(key, value);
			}
		}
		
		return map;
	}
	/**
	 * 获取startIndex
	 * @param rows 分页大小
	 * @param page	目标页码
	 * @param records	总记录数
	 * @return
	 */
	public Integer getStartIndex(Integer rows,Integer page,Integer records){
		this.rows=rows;
		this.page=page;
		this.records=records;
		
		if(records.intValue()<=rows.intValue()){
			total=1;
		}else if(records.intValue()%rows.intValue()>0){
			total=records.intValue()/rows.intValue()+1;
		}else{
			total=records.intValue()/rows.intValue();
		}
		
		this.startIndex=rows*(page-1);
		
		return this.startIndex;
	}
	/**
	 * 将传来的记录maps并上上面的rows,total,page拼接成jqGrid需要的json
	 * 在getStartIndex()之后使用
	 * @param maps
	 * @return
	 */
	public String getJqJSON(List<Map<String,Object>> maps){
		String json=new String("{\"total\":\""+total+"\",\"page\":\""+page+"\",\"records\":\""+records+"\",\"rows\":" +this.buildRecord(maps)+"}");
		return json;
	}
	
	private String buildRecord(List<Map<String,Object>> maps){
		
		StringBuffer json=new StringBuffer("[");
		
		if(maps!=null){
			for(Map<String,Object> map:maps){
				map=this.coverRecord(map);
				
				json.append("{");
				Iterator<String> it=map.keySet().iterator();
				while(it.hasNext()){
					String key=it.next();
					json.append("\""+key+"\":\""+map.get(key)+"\",");
				}
				json.deleteCharAt(json.length()-1);
				json.append("},");
			}
			json.deleteCharAt(json.length()-1);
		}
		json.append("]");
		return json.toString();
	}
	/**
	 * 将遍历出来的每一条记录走一次此方法<br>
	 * 只要覆盖这个方法即可对遍历出的记录作处理
	 * @param record
	 * @return
	 */
	protected Map<String,Object> coverRecord(Map<String,Object> record){
		return record;
	}
}
